package com.xnx3.kefu.core.pluginManage.interfaces.manage;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;
import com.xnx3.ScanClassUtil;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.j2ee.vo.BaseVO;

/**
 * kefu.js 追加相关
 * @author 管雷鸣
 *
 */
@Component(value="KefuJsPluginForKefuMessage")
public class KefuJsPluginManage {
	//这里开启项目时，便将有关此的插件加入此处
	public static List<Class<?>> classList;
	static{
		classList = new ArrayList<Class<?>>();
		
		try {
			List<Class<?>> allClassList = ScanClassUtil.getClasses("com.xnx3");
			classList = ScanClassUtil.searchByInterfaceName(allClassList, "com.xnx3.kefu.core.pluginManage.interfaces.KefuJsInterface");
			for (int i = 0; i < classList.size(); i++) {
				ConsoleUtil.info("装载 Kefu KefuJsInterface 插件："+classList.get(i).getName());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 向kefu.js中追加 js 资源文件。会在kefu.init() 之前被追加。
	 * @return 被追加的js资源文件的url，建议是绝对路径。其中可以用 {kefu.api} 调取 kefu.properties 中配置的信息。如设置为  {kefu.api}/plugin/abcd/plugin.js
	 */
	public static List<String> kefuJsAppendJsFile(HttpServletRequest request){
		List<String> list = new ArrayList<String>();
		
		for (int i = 0; i < classList.size(); i++) {
			try {
				Class<?> c = classList.get(i);
				Object invoke = null;
				invoke = c.newInstance();
				//运用newInstance()来生成这个新获取方法的实例  
				Method m = c.getMethod("kefuJsAppendJsFile",new Class[]{HttpServletRequest.class});	//获取要调用方法
				Object o = m.invoke(invoke, new Object[]{request});
				if(o != null){
					List<String> plist = (List<String>) o;
					if(plist.size() > 0) {
						list.addAll(plist);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return list;
	}
	

	/**
	 * 当客户端发送正常消息进行交流时触发。这个已经抛除了打开链接、以及常见问题的自动匹配，触发这个的都是用户主动发送的消息
	 * @param kefu.js 聊天窗口中要执行的js
	 */
	public static String kefuJsAppendJsCode(HttpServletRequest request){
		StringBuffer sb = new StringBuffer();
		
		for (int i = 0; i < classList.size(); i++) {
			try {
				Class<?> c = classList.get(i);
				Object invoke = null;
				invoke = c.newInstance();
				//运用newInstance()来生成这个新获取方法的实例  
				Method m = c.getMethod("kefuJsAppendJsCode",new Class[]{HttpServletRequest.class});	//获取要调用方法
				Object o = m.invoke(invoke, new Object[]{request});
				if(o != null){
					BaseVO vo = (BaseVO) o;
					if(vo.getResult() - BaseVO.SUCCESS == 0){
						if(vo.getInfo() != null) {
							sb.append(vo.getInfo());
						}
					}else {
						ConsoleUtil.info(c.getName()+" , info："+vo.getInfo());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		if(sb.length() > 0) {
			return sb.toString();
		}else{
			return "";
		}
	}
	
	
	
}
